package com.leyou.order.utils;

import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayConfig;
//import com.github.wxpay.sdk.WXPayConfigImpl;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * 微信支付工具类
 */
@Slf4j
@Component
public class PayHelper {

    @Autowired
    private WXPay wxPay;
//    @Autowired
//    private WXPayConfig wxPayConfig;

    /**
     * 调用微信的统一下单接口
     * @param body
     * @param orderId
     * @param totalFee
     * @return codeUrl
     */
    public  String unifiedorder(String body,Long orderId,Long totalFee){
        Map<String,String> map = new HashMap<>();
        map.put("body",body);
        map.put("out_trade_no",orderId.toString());
        map.put("total_fee",totalFee.toString());
        map.put("spbill_create_ip","127.0.0.1");
//        map.put("notify_url",wxPayConfig.get());
//        map.put("trade_type",wxPayConfig.getPayType());

        try {
            Map<String, String> result = wxPay.unifiedOrder(map);
            if(CollectionUtils.isEmpty(result)){
                throw new LyException(ExceptionEnum.PAY_URL_ERROR);
            }
            log.info("微信支付返回结果，result={}",result);
            String codeUrl = result.get("code_url");
            return codeUrl;
        } catch (Exception e) {
            e.printStackTrace();
            throw new LyException(ExceptionEnum.PAY_URL_ERROR);
        }
    }

    //校验签名的算法
    public void isValidSign(Map<String, String> result) throws Exception {
//        boolean boo1 = WXPayUtil.isSignatureValid(result, /*wxPayConfig.g()*/, WXPayConstants.SignType.MD5);
//        boolean boo2 = WXPayUtil.isSignatureValid(result, wxPayConfig.getKey(), WXPayConstants.SignType.HMACSHA256);
//        if (!boo1 && !boo2) {
//            throw new RuntimeException("【微信支付回调】签名有误");
//        }
    }

    //另外，支付是否成功，需要校验业务状态才知道，我们在PayHelper编写一个校验业务状态的方法
    public void checkResultCode(Map<String, String> result) {
        // 检查业务状态
        String resultCode = result.get("result_code");
        if ("FAIL".equals(resultCode)) {
            log.error("【微信支付】微信支付业务失败，错误码：{}，原因：{}", result.get("err_code"), result.get("err_code_des"));
            throw new RuntimeException("【微信支付】微信支付业务失败");
        }
    }
}
